# @Author:黄景涛
# @Date: 2024/3/31

import sys
from codes.basic_requests import RequestUtil
from utils.log.logger import logger
from codes.hjt_extract.extract_engine import GlobalExtract, LocalExtract

# 全局变量池
f_name = 'extract.yaml'


def send_request(case, self=None):
    logger.info(RequestUtil.start_msg)
    try:
        try:
            test_cls = self.__class__
            test_module = sys.modules[self.__module__]
            req = RequestUtil(case, test_module, test_cls)
            # 1.处理请求数据; 2.发送请求
            req.send_request()
            case_data = req.case_data
            response_data = req.suffix_response
        except:
            raise

            # 3.提取变量
        try:
            # 提取全局变量，保存至文件中
            GlobalExtract(case_data, response_data, f_name).main()
            # 提取局部变量，保存至test模块、test类中
            local_vars: dict = LocalExtract(case_data, response_data).main()
            extract_module_vars: dict = local_vars.get('module_')
            extract_class_vars: dict = local_vars.get('class_')
            if extract_module_vars is not None:
                for k, v in extract_module_vars.items():
                    setattr(test_module, k, v)
            if extract_class_vars is not None:
                for k, v in extract_class_vars.items():
                    setattr(test_cls, k, v)
        except Exception as e:
            logger.info(f'变量提取有误，{e}')

        try:
            # 4.断言
            req.validate()
        except:
            raise
    except:
        raise
    finally:
        logger.info(RequestUtil.end_msg)
